<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>点击单元格更改其背景颜色</title>
<script>
  // 创建单元格，规格为4×4
  function addCell() {
    var t = document.getElementById("t1");
    for (var a = 1; a <= 4; a++) {
      var etr = document.createElement("tr");
      t.appendChild(etr);
      var str = "";
      for (var b = 1; b <= 4; b++) {
        etr.innerHTML = str = str + "<td width='50' onclick='changeColor(event)'>" + a * b + "</td>";
      }
      str = "";
    }
  }
  // 更改单元格的背景色
  function changeColor(event) {
    // 等价于event.target.style.backgroundColor
    var c = event.target.bgColor;
    if (c !== "red")
      event.target.bgColor = "red";
    else
      event.target.bgColor = "white";
  }
</script>
</head>
<body onload="addCell()">
  <div align="center">
    <table id="t1" style="width: 200px; border-collapse: collapse" border="1"></table>
  </div>
</body>
</html>
